"use client"

import { useState } from "react"
import { View, Text, TouchableOpacity, StyleSheet, SafeAreaView, ScrollView, ActivityIndicator } from "react-native"
import { useDeviceInfo } from "../hooks/useDeviceInfo"
import { createResponsiveStyles } from "../styles/responsive"

interface Device {
  id: string
  name: string
  rssi: number
  status: "available" | "connecting" | "connected"
}

interface BluetoothScreenProps {
  onConnect: () => void
}

export default function BluetoothScreen({ onConnect }: BluetoothScreenProps) {
  const [isScanning, setIsScanning] = useState(false)
  const [devices, setDevices] = useState<Device[]>([])
  const [connectedCount, setConnectedCount] = useState(0)
  const deviceInfo = useDeviceInfo()
  const responsive = createResponsiveStyles(deviceInfo)
  const styles = createStyles(responsive, deviceInfo)

  const mockDevices: Device[] = [
    { id: "1", name: "ESP32-01", rssi: -45, status: "available" },
    { id: "2", name: "ESP32-02", rssi: -52, status: "available" },
    { id: "3", name: "ESP32-03", rssi: -38, status: "available" },
    { id: "4", name: "ESP32-04", rssi: -61, status: "available" },
  ]

  const startScan = () => {
    setIsScanning(true)
    setDevices([])

    setTimeout(() => setDevices([mockDevices[0]]), 500)
    setTimeout(() => setDevices([mockDevices[0], mockDevices[1]]), 1000)
    setTimeout(() => setDevices([mockDevices[0], mockDevices[1], mockDevices[2]]), 1500)
    setTimeout(() => {
      setDevices(mockDevices)
      setIsScanning(false)
    }, 2000)
  }

  const connectDevice = (deviceId: string) => {
    setDevices((prev) => prev.map((device) => (device.id === deviceId ? { ...device, status: "connecting" } : device)))

    setTimeout(() => {
      setDevices((prev) => prev.map((device) => (device.id === deviceId ? { ...device, status: "connected" } : device)))
      setConnectedCount((prev) => prev + 1)
    }, 2000)
  }

  const renderDeviceStatus = (device: Device) => {
    switch (device.status) {
      case "connected":
        return (
          <View style={styles.statusConnected}>
            <Text style={styles.statusConnectedText}>✓ 已连接</Text>
          </View>
        )
      case "connecting":
        return (
          <View style={styles.statusConnecting}>
            <ActivityIndicator size="small" color="#f97316" />
            <Text style={styles.statusConnectingText}>连接中</Text>
          </View>
        )
      default:
        return (
          <TouchableOpacity style={styles.connectButton} onPress={() => connectDevice(device.id)}>
            <Text style={styles.connectButtonText}>连接</Text>
          </TouchableOpacity>
        )
    }
  }

  return (
    <SafeAreaView style={styles.container}>
      <ScrollView contentContainerStyle={styles.scrollContent}>
        {/* Header */}
        <View style={styles.header}>
          <View style={styles.headerContent}>
            <View style={styles.headerLeft}>
              <View style={styles.logo} />
              <Text style={styles.headerTitle}>DEVICE CONNECTION</Text>
            </View>
            <Text style={styles.headerStatus}>已连接: {connectedCount}/4 设备</Text>
          </View>
          <View style={styles.headerBorder} />
        </View>

        <View style={styles.mainContent}>
          {/* Status Section */}
          <View style={styles.statusSection}>
            <Text style={styles.mainTitle}>BLUETOOTH_{"\n"}DEVICES</Text>

            <View style={styles.statusCard}>
              <View style={styles.statusHeader}>
                <Text style={styles.statusLabel}>连接状态</Text>
                <View style={styles.orangeDot} />
              </View>
              <Text style={styles.statusValue}>{connectedCount}</Text>
              <Text style={styles.statusSubtext}>设备已连接</Text>
              <View style={styles.progressBar}>
                <View style={[styles.progressFill, { width: `${(connectedCount / 4) * 100}%` }]} />
              </View>
            </View>

            <TouchableOpacity
              style={[styles.scanButton, isScanning && styles.scanButtonDisabled]}
              onPress={startScan}
              disabled={isScanning}
            >
              {isScanning ? (
                <View style={styles.scanButtonContent}>
                  <ActivityIndicator size="small" color="#ffffff" />
                  <Text style={styles.scanButtonText}>扫描中...</Text>
                </View>
              ) : (
                <Text style={styles.scanButtonText}>📡 扫描设备</Text>
              )}
            </TouchableOpacity>
          </View>

          {/* Device List */}
          <View style={styles.deviceSection}>
            <Text style={styles.sectionTitle}>发现的设备</Text>
            <View style={styles.deviceGrid}>
              {devices.map((device) => (
                <View key={device.id} style={styles.deviceCard}>
                  <View style={styles.deviceHeader}>
                    <View style={styles.deviceInfo}>
                      <Text style={styles.deviceIcon}>📱</Text>
                      <Text style={styles.deviceName}>{device.name}</Text>
                    </View>
                    {renderDeviceStatus(device)}
                  </View>

                  <View style={styles.deviceDetails}>
                    <View style={styles.deviceDetailRow}>
                      <Text style={styles.deviceDetailLabel}>信号强度</Text>
                      <Text style={styles.deviceDetailValue}>{device.rssi} dBm</Text>
                    </View>
                    <View style={styles.deviceDetailRow}>
                      <Text style={styles.deviceDetailLabel}>状态</Text>
                      <Text style={styles.deviceDetailValue}>
                        {device.status === "available" && "可连接"}
                        {device.status === "connecting" && "连接中"}
                        {device.status === "connected" && "已连接"}
                      </Text>
                    </View>
                  </View>
                </View>
              ))}

              {devices.length === 0 && !isScanning && (
                <View style={styles.emptyState}>
                  <Text style={styles.emptyStateIcon}>📱</Text>
                  <Text style={styles.emptyStateText}>未发现设备，请点击扫描</Text>
                </View>
              )}
            </View>
          </View>
        </View>

        {/* Bottom Action */}
        <View style={styles.bottomSection}>
          <View style={styles.bottomBorder} />
          <View style={styles.bottomContent}>
            <TouchableOpacity
              style={[styles.continueButton, connectedCount === 0 && styles.continueButtonDisabled]}
              onPress={onConnect}
              disabled={connectedCount === 0}
            >
              <Text style={styles.continueButtonText}>{connectedCount > 0 ? "继续训练" : "请先连接设备"}</Text>
            </TouchableOpacity>
          </View>
        </View>
      </ScrollView>
    </SafeAreaView>
  )
}

const createStyles = (responsive: any, deviceInfo: any) =>
  StyleSheet.create({
    container: {
      flex: 1,
      backgroundColor: "#ffffff",
    },
    scrollContent: {
      flexGrow: 1,
      padding: responsive.containerPadding,
    },
    header: {
      marginBottom: responsive.spacing.xxl,
    },
    headerContent: {
      flexDirection: "row",
      justifyContent: "space-between",
      alignItems: "center",
      paddingBottom: responsive.spacing.lg,
    },
    headerLeft: {
      flexDirection: "row",
      alignItems: "center",
    },
    logo: {
      width: responsive.sizes.header,
      height: responsive.sizes.header,
      backgroundColor: "#f97316",
      marginRight: responsive.spacing.md,
    },
    headerTitle: {
      fontSize: responsive.fontSize.sm,
      fontWeight: "500",
      color: "#000000",
    },
    headerStatus: {
      fontSize: responsive.fontSize.sm,
      color: "#666666",
    },
    headerBorder: {
      height: 1,
      backgroundColor: "#e5e7eb",
    },
    mainContent: {
      flex: 1,
      // 强制使用垂直布局确保内容可见
      flexDirection: "column",
      gap: responsive.spacing.lg,
    },
    statusSection: {
      paddingHorizontal: responsive.spacing.md,
      marginBottom: responsive.spacing.lg,
    },
    deviceSection: {
      paddingHorizontal: responsive.spacing.md,
      flex: 1,
    },
    mainTitle: {
      fontSize: responsive.fontSize.title,
      fontWeight: "bold",
      color: "#000000",
      lineHeight: responsive.fontSize.title * 1.2,
      marginBottom: responsive.spacing.xl,
    },
    statusCard: {
      borderWidth: 1,
      borderColor: "#e5e7eb",
      padding: responsive.spacing.lg,
      marginBottom: responsive.spacing.xl,
    },
    statusHeader: {
      flexDirection: "row",
      justifyContent: "space-between",
      alignItems: "center",
      marginBottom: responsive.spacing.md,
    },
    statusLabel: {
      fontSize: responsive.fontSize.sm,
      fontWeight: "500",
      color: "#000000",
    },
    orangeDot: {
      width: 12,
      height: 12,
      backgroundColor: "#f97316",
      borderRadius: 6,
    },
    statusValue: {
      fontSize: responsive.fontSize.title,
      fontWeight: "bold",
      color: "#000000",
      marginBottom: responsive.spacing.xs,
    },
    statusSubtext: {
      fontSize: responsive.fontSize.sm,
      color: "#666666",
      marginBottom: responsive.spacing.md,
    },
    progressBar: {
      height: 8,
      backgroundColor: "#f3f4f6",
    },
    progressFill: {
      height: 8,
      backgroundColor: "#f97316",
    },
    scanButton: {
      height: responsive.sizes.button,
      backgroundColor: "#3b82f6",
      justifyContent: "center",
      alignItems: "center",
    },
    scanButtonDisabled: {
      backgroundColor: "#9ca3af",
    },
    scanButtonContent: {
      flexDirection: "row",
      alignItems: "center",
      gap: responsive.spacing.xs,
    },
    scanButtonText: {
      fontSize: responsive.fontSize.md,
      fontWeight: "500",
      color: "#ffffff",
    },
    deviceGrid: {
      gap: responsive.spacing.md,
      // 强制垂直布局
      flexDirection: "column",
    },
    deviceCard: {
      borderWidth: 1,
      borderColor: "#e5e7eb",
      padding: responsive.spacing.md,
      marginBottom: responsive.spacing.sm,
      width: "100%", // 确保占满宽度
    },
    deviceHeader: {
      flexDirection: "row",
      justifyContent: "space-between",
      alignItems: "center",
      marginBottom: responsive.spacing.md,
    },
    deviceInfo: {
      flexDirection: "row",
      alignItems: "center",
      gap: responsive.spacing.sm,
    },
    deviceIcon: {
      fontSize: responsive.fontSize.xl,
    },
    deviceName: {
      fontSize: responsive.fontSize.md,
      fontWeight: "500",
      color: "#000000",
    },
    deviceDetails: {
      gap: responsive.spacing.xs,
    },
    deviceDetailRow: {
      flexDirection: "row",
      justifyContent: "space-between",
    },
    deviceDetailLabel: {
      fontSize: responsive.fontSize.sm,
      color: "#666666",
    },
    deviceDetailValue: {
      fontSize: responsive.fontSize.sm,
      fontWeight: "500",
      color: "#000000",
    },
    statusConnected: {
      backgroundColor: "#dcfce7",
      paddingHorizontal: responsive.spacing.sm,
      paddingVertical: responsive.spacing.xs,
    },
    statusConnectedText: {
      fontSize: responsive.fontSize.xs,
      color: "#166534",
      fontWeight: "500",
    },
    statusConnecting: {
      flexDirection: "row",
      alignItems: "center",
      gap: responsive.spacing.xs,
      backgroundColor: "#fef3c7",
      paddingHorizontal: responsive.spacing.sm,
      paddingVertical: responsive.spacing.xs,
    },
    statusConnectingText: {
      fontSize: responsive.fontSize.xs,
      color: "#92400e",
      fontWeight: "500",
    },
    connectButton: {
      backgroundColor: "#f97316",
      paddingHorizontal: responsive.spacing.md,
      paddingVertical: responsive.spacing.xs,
    },
    connectButtonText: {
      fontSize: responsive.fontSize.sm,
      fontWeight: "500",
      color: "#ffffff",
    },
    emptyState: {
      alignItems: "center",
      justifyContent: "center",
      padding: responsive.spacing.xxl,
      borderWidth: 1,
      borderColor: "#e5e7eb",
    },
    emptyStateIcon: {
      fontSize: responsive.fontSize.xxl * 2,
      marginBottom: responsive.spacing.md,
    },
    emptyStateText: {
      fontSize: responsive.fontSize.md,
      color: "#666666",
    },
    bottomSection: {
      marginTop: responsive.spacing.xxl,
    },
    bottomBorder: {
      height: 1,
      backgroundColor: "#e5e7eb",
      marginBottom: responsive.spacing.xl,
    },
    bottomContent: {
      alignItems: "flex-end",
    },
    continueButton: {
      height: responsive.sizes.button,
      backgroundColor: "#f97316",
      paddingHorizontal: responsive.spacing.xl,
      justifyContent: "center",
      alignItems: "center",
      minWidth: deviceInfo.isSmallPhone ? "100%" : 200,
    },
    continueButtonDisabled: {
      backgroundColor: "#d1d5db",
    },
    continueButtonText: {
      fontSize: responsive.fontSize.md,
      fontWeight: "500",
      color: "#ffffff",
    },
    sectionTitle: {
      fontSize: responsive.fontSize.lg,
      fontWeight: "600",
      color: "#000000",
      marginBottom: responsive.spacing.md,
    },
  })
